package com.wx.config;

import com.wx.filter.CustomerAuthenticationFilter;
import com.wx.filter.CustomerUsernamePasswordAuthenticationFilter;
import com.wx.handler.security.*;
import com.wx.service.impl.SecurityUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private SecurityUserDetailsService securityUserDetailsService;

    @Resource
    private CustomerAuthenticationFailureHandler customerAuthenticationFailureHandler;

    @Resource
    private CustomerAuthenticationSuccessHandler customerAuthenticationSuccessHandler;

    @Resource
    private CustomerLoginAuthEntryPoint customerLoginAuthEntryPoint;

    @Resource
    private CustomerAuthenticationAccessDeniedHandler customerAuthenticationAccessDeniedHandler;

    @Resource
    private CustomerLogoutSuccessHandler customerLogoutSuccessHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.authenticationProvider(authenticationProvider());
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(securityUserDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public CustomerUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {
        CustomerUsernamePasswordAuthenticationFilter filter = new CustomerUsernamePasswordAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(customerAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(customerAuthenticationFailureHandler);
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityUserDetailsService).passwordEncoder(passwordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAt(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.cors().and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(
                        "/*/v2/api-docs",
                        "/v2/api-docs",
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/actuator/**",
                        "/doc.html",
                        "/webjars/**",
                        "/validateCode/**",
                        "/api/**",
                        "/wx/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(myAuthenticationFilter())
                .addFilter(new CustomerAuthenticationFilter(authenticationManager()))
                .exceptionHandling().accessDeniedHandler(customerAuthenticationAccessDeniedHandler)
                .authenticationEntryPoint(customerLoginAuthEntryPoint)
                .and()
                .logout()
                .logoutSuccessHandler(customerLogoutSuccessHandler);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.httpFirewall(httpFirewall());
        web.ignoring().antMatchers("/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html",
                "/webjars/**"
        );
    }

    @Bean
    public HttpFirewall httpFirewall() {
        return new DefaultHttpFirewall();
    }

}
